<template>
  <div>
    <div style="margin-top: 20px; display: flex; align-items: center;">
      <template>
        <el-select v-model="value" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </template>

      <el-input
          placeholder="请输入内容"
          v-model="input"
          clearable>
      </el-input>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="searchData1">搜索</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <el-input
          v-model="search"
          icon="el-icon-search"
          placeholder="关键字搜索"
          size="mini"
          style="margin-left: 10px;"
          @input="searchData"
      />

      <el-popover
          placement="right"
          trigger="click"
          width="100"
      >
        <div class="checkbox-container">
          <el-checkbox v-model="displayTheList.showProcurementStatus">采购状态</el-checkbox>
          <el-checkbox v-model="displayTheList.RequestQuoteStatus">询报价状态</el-checkbox>
          <el-checkbox v-model="displayTheList.PaymentStatus">付款状态</el-checkbox>
          <el-checkbox v-model="displayTheList.Supplier">供应商</el-checkbox>
          <el-checkbox v-model="displayTheList.PurchaseRequisitionNumber">采购申请编号</el-checkbox>
          <el-checkbox v-model="displayTheList.DateApplication">申请日期</el-checkbox>
          <el-checkbox v-model="displayTheList.Applicant">申请人</el-checkbox>
          <el-checkbox v-model="displayTheList.ApplicantDepartment">申请人归属部门</el-checkbox>
          <el-checkbox v-model="displayTheList.ApplicatDate">申请日期</el-checkbox>
          <el-checkbox v-model="displayTheList.ArrivalDate">到货计划日期</el-checkbox>
          <el-checkbox v-model="displayTheList.SourcesDemand">需求来源</el-checkbox>
          <el-checkbox v-model="displayTheList.Warehouse">入库仓库</el-checkbox>
          <el-checkbox v-model="displayTheList.ArrivalAddress">到货地址</el-checkbox>
          <el-checkbox v-model="displayTheList.ProductName">产品名</el-checkbox>
          <el-checkbox v-model="displayTheList.ProductNumber">产品编号</el-checkbox>
          <el-checkbox v-model="displayTheList.Brand">品牌</el-checkbox>
          <el-checkbox v-model="displayTheList.ProductModels">规格型号</el-checkbox>
          <el-checkbox v-model="displayTheList.Unit">单位</el-checkbox>
          <el-checkbox v-model="displayTheList.PurchaseDemandQuantity">采购需求数量</el-checkbox>
          <el-checkbox v-model="displayTheList.PurchaseQuantity">已采购数量</el-checkbox>
          <el-checkbox v-model="displayTheList.Remarks">备注</el-checkbox>
          <el-checkbox v-model="displayTheList.EnterPerson">提交人</el-checkbox>
          <el-checkbox v-model="displayTheList.EnterTime">提交时间</el-checkbox>
          <el-checkbox v-model="displayTheList.UpdateTime">更新日期</el-checkbox>
        </div>
        <el-button slot="reference" icon="el-icon-notebook-2" size="small">显示字段</el-button>
      </el-popover>
    </div>
    <el-table
        ref="multipleTable"
        :data="filteredData"
        v-loading="loading"
        :default-sort="{prop: 'date', order: 'descending'}"
        border
        highlight-current-row
        style="width: 100%"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        @current-change="handleCurrentChange"
        @row-click="handleRowClick"
    >
      <el-table-column
          fixed
          type="selection"
          width="55"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.showProcurementStatus"
          label="采购状态"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.RequestQuoteStatus"
          label="询报价状态"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.PaymentStatus"
          label="付款状态"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.Supplier"
          label="供应商"
          prop="supplier.supplierName"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.PurchaseRequisitionNumber"
          label="采购申请编号"
          prop="purchaseApply.code"
          sortable
          width="160"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.DateApplication"
          label="申请日期"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.Applicant"
          label="申请人"
          prop="employee.name"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ApplicantDepartment"
          label="申请人归属部门"
          prop="companyDepartment.name"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ApplicatDate"
          label="申请日期"
          sortable
          width="210"
      >
        <template #default="scope">
          {{ formatDate(scope.row.purchaseApply.enterTime) }}
        </template>
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ArrivalDate"
          label="到货计划日期"
          sortable
          width="210"
      >
        <template #default="scope">
          {{ formatDateDay(scope.row.purchaseApply.deliveryDemandTime) }}
        </template>
      </el-table-column>
      <el-table-column
          v-if="displayTheList.SourcesDemand"
          label="需求来源"
          width="120"
      >
        <template #default="scope">
          {{ getSourceText(scope.row.purchaseApply.source) }}
        </template>
      </el-table-column>
      <el-table-column
          v-if="displayTheList.Warehouse"
          label="入库仓库"
          prop="warehouse.name"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ArrivalAddress"
          label="到货地址"
          prop="warehouse.address"
          width="300"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ProductName"
          label="产品名"
          prop="productShow.productName"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ProductNumber"
          label="产品编号"
          prop="productShow.productCode"
          width="180"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.Brand"
          label="品牌"
          prop="productShow.productBrand"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.ProductModels"
          label="规格型号"
          prop="productShow.productAttribute"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.Unit"
          label="单位"
          prop="productShow.priductUnit"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.PurchaseDemandQuantity"
          label="采购需求数量"
          prop="purchaseProductDetails.purchaseNum"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.Remarks"
          label="备注"
          prop="purchaseApply.remarks"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.EnterPerson"
          label="提交人"
          prop="productWarehouse.enterPerson"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.EnterTime"
          label="提交时间"
          width="210"
      >
        <template #default="scope">
          {{ formatDate(scope.row.purchaseApply.enterTime) }}
        </template>
      </el-table-column>
      <el-table-column
          v-if="displayTheList.UpdateTime"
          label="更新日期"
          width="120"
      >
      </el-table-column>
      <el-table-column
          v-if="displayTheList.PurchaseQuantity"
          label="已采购数量"
          prop="purchaseApply.purchasedQuantity"
          width="120"
      >
      </el-table-column>
    </el-table>
    <el-dialog
        title="需求信息"
        :visible.sync="dialogVisible"
        width="30%">
      <span>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChangePage"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      search: '',
      mainData: [],
      value: '',
      loading: false,
      displayTheList: {
        showProcurementStatus: true,
        RequestQuoteStatus: true,
        PaymentStatus: true,
        Supplier: true,
        PurchaseRequisitionNumber: true,
        DateApplication: true,
        Applicant: true,
        ApplicantDepartment: true,
        ApplicatDate: true,
        ArrivalDate: true,
        SourcesDemand: true,
        Warehouse: true,
        ArrivalAddress: true,
        ProductName: true,
        ProductNumber: true,
        Brand: true,
        ProductModels: true,
        Unit: true,
        PurchaseDemandQuantity: true,
        PurchaseQuantity: true,
        Remarks: true,
        EnterPerson: true,
        EnterTime: true,
        UpdateTime: true
      },
      input:'',
      options: [{
        value: '1',
        label: '产品名'
      }, {
        value: '2',
        label: '供应商'
      },{
        value: '3',
        label: '采购申请编号'
      },{
        value: '4',
        label: '仓库名'
      }
      ],
      multipleSelection: [],
      currentRow: null,
      filteredData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      detailData: {},
    };
  },
  created() {
    this.getPurchaseProductDetails();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    searchData1 () {
      this.getPurchaseProductDetails();
},
    async getPurchaseProductDetails() {
      this.loading = true;
      try {
        const response = await axios.get('manage/purchaseProductDetails/list', {
          params: {
            filterCriteria: this.value,
            conditions: this.input,
            page: this.currentPage,
            pageSize: this.pageSize
          }
        });
        this.mainData = response.data.data.records;
        this.filteredData = this.mainData;
        this.total = response.data.data.total;
        console.log(this.mainData);
      } catch (error) {
        console.error('获取数据失败', error);
      } finally {
        this.loading = false;
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
    },
    formatDateDay(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}年${month}月${day}日`;
    },
    getSourceText(source) {
      if (source === '3') return '补货';
      if (source === '6') return '库存预警';
      if (source === '9') return '工单需求';
      return '';
    },
    searchData() {
      if (!this.search) {
        this.filteredData = this.mainData;
        return;
      }
      this.filteredData = this.mainData.filter(row => {
        const fields = [
          row.supplier?.supplierName,
          row.purchaseApply?.code,
          row.employee?.name,
          row.companyDepartment?.name,
          this.formatDate(row.purchaseApply?.enterTime),
          this.formatDateDay(row.purchaseApply?.deliveryDemandTime),
          this.getSourceText(row.purchaseApply?.source),
          row.warehouse?.name,
          row.warehouse?.address,
          row.productShow?.productName,
          row.productShow?.productCode,
          row.productShow?.productBrand,
          row.productShow?.productAttribute,
          row.productShow?.priductUnit,
          row.purchaseProductDetails?.purchaseNum,
          row.purchaseApply?.remarks,
          row.productWarehouse?.enterPerson,
          this.formatDate(row.purchaseApply?.enterTime),
          row.purchaseApply?.purchasedQuantity
        ];
        return fields.some(field => {
          if (typeof field === 'string') {
            return field.includes(this.search);
          }
          return false;
        });
      });
    },
    async batchDelete() {
      const ids = this.multipleSelection.map(item => item.purchaseProductDetails.id);
      console.log(ids);
      if (ids.length === 0) {
        this.$message.warning('请选择要删除的记录');
        return;
      }
      try {
        await axios.delete('manage/purchaseProductDetails/batchDelete', { data: ids });
        this.$message.success('删除成功');
        this.getPurchaseProductDetails();
      } catch (error) {
        this.$message.error('删除失败');
        console.error('删除失败', error);
      }
    },
    handleRowClick(row) {
      this.detailData = row;
      this.dialogVisible = true;
      console.log(this.detailData);
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getPurchaseProductDetails();
    },
    handleCurrentChangePage(newPage) {
      this.currentPage = newPage;
      this.getPurchaseProductDetails();
    }
  }
};
</script>

<style scoped>
.checkbox-container {
  height: 300px;
  overflow-y: auto;
}
</style>